//
//  CreateJobReviewDetailVC.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/7.
//

import UIKit
import SwiftyJSON
import HandyJSON
class CreateJobReviewDetailVC: BaseViewController {
    let customView = CreateJobReviewDetailView(topBGImageName: "createjob_installdate_top_bg")
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    //
    private func initUI(){
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.review())
        //继续下一步System Details
        self.customView.continueClosure = {[weak self] in
            guard let strongSelf = self else { return  }
            let checkMsg = strongSelf.checkIfEverythingIsValid()
            if checkMsg.count > 0{//校验不通过
                Tool().showAlertViewWithOneBtn(message: checkMsg,messageTextAlignment: .left)
            }else{//校验通过
                strongSelf.toContinue()
            }
        }
    }
    //MARK: - 校验是否数据合法
    private func checkIfEverythingIsValid()->String{
        var retStr: String = ""
        //1.panels
        let panels = CreateJobModelHelper.shared.createJobViewModel.systemDetail.panels
        for model in panels{
            if model.valid_flag == false{
                retStr += "* The panel model " + model.model + " is invalid according to the current installation date\n\n"
            }
        }
        //2.inverters
        let inverters = CreateJobModelHelper.shared.createJobViewModel.systemDetail.inverters
        for model in inverters{
            if model.valid_flag == false{
                retStr += "* The inverter Model " + model.inverter_model + " is is invalid according to the current installation date\n\n"
            }
        }
        //3.installer
        if CreateJobModelHelper.shared.createJobViewModel.installerDetail.installer_valid_flag ==  false{
            retStr += "* Installer does not employed by the current company\n\n"
        }
        //4.designer
        if CreateJobModelHelper.shared.createJobViewModel.installerDetail.designer_valid_flag ==  false{
            retStr += "* Designer does not employed by the current company\n\n"
        }
        //5.electrician
        if CreateJobModelHelper.shared.createJobViewModel.installerDetail.electrician_valid_flag ==  false{
            retStr += "* Electrician does not employed by the current company\n\n"
        }
        //6.pickup address
        if CreateJobModelHelper.shared.createJobViewModel.installerDetail.delivery_address_valid_flag == false{
            retStr += "* The pick-up address does not belong to the current company\n\n"
        }
        if retStr.count > 0 {
            retStr = String(retStr.prefix(retStr.count - 2))
        }
        return retStr
    }
    //
    private func toContinue(){
        //先校验spv check ，确认是否开启spv
        InstallationDetailVCHelper.shared.validSPVCheckBeforeNextOperation(panels: CreateJobModelHelper.shared.createJobViewModel.systemDetail.panels, companyID: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id) { spvCheckFlag in
            if spvCheckFlag {//需要提示是否开启spv
                self.showValidSPVCheckView()
            }else{
                self.createJob()
            }
        }
    }
    
    //MARK: - 刷新system detail的数据
    private func loadData(){
        CreateJobModelHelper.shared.systemInfoObserver.onNext(CreateJobModelHelper.shared.createJobViewModel.systemDetail)
    }
    //MARK: - create job API
    private func createJob(){
        let service = CreateJobService()
        service.setBlockAfterNetwork { [weak self] (result, otherInfo) in
            ModelViewUtil.shared.hideLoadingView()
            guard let strongSelf = self else {return}
            guard let navi = strongSelf.navigationController else {return}
            guard let model = result as? PVDDetailModel else {return}
            //
            if navi.viewControllers.count > 0{
                var controllers: [UIViewController] = [navi.viewControllers[0]]
                let vc = CreateJobSuccessVC()
                vc.model = model
                vc.hidesBottomBarWhenPushed = true
                controllers.append(vc)
                navi.setViewControllers(controllers, animated: true)
            }

        } errorBlock: { code, error in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error)
        }
        ModelViewUtil.shared.showLoadingView("Creating Job...")
        service.createJob(CreateJobModelHelper.shared.createJobViewModel)
    }
    //MARK: - 显示Valid SPV Check
    private func showValidSPVCheckView(){
        let view = CreateJobValidSPVCheckView()
        view.closure = { [weak self] spvCheck in
            CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.spv_check = spvCheck
            self?.createJob()
        }
        self.view.addSubview(view)
        view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        //设置数据放在这里，是为了编辑的时候返回后也能及时更新数据
        self.customView.setData()
    }
}
